
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:flutter_trip/pages/search_page.dart';
import 'package:flutter_trip/pages/speak_page.dart';
import 'package:flutter_trip/widget/loading_container.dart';

import '../dao/Home_dao.dart';
import '../model/home_model.dart';
import '../widget/fwebview.dart';
import '../widget/grid_nav.dart';
import '../widget/local_nav.dart';
import '../widget/sales_box.dart';
import '../widget/search_textfiled.dart';
import '../widget/sub_nav.dart';
import '../widget/loading_container.dart';
const APPBAR_SCOLL_MAX_OFFSET = 100;
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double navcAlpha = 0;
  HomeModel? _homeModel;
  bool _isLoading = true;
  List<CommonModel> bannerList = [];
  List<CommonModel> subNavList = [];
  List<CommonModel> localNavList = [];
  GridNavModel? gridNavmodel;
  SalesBoxModel? salesBoxModel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _refresh();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff2f2f2),
      body: LoadingContainer(
        isLoading: _isLoading,
        child: Stack(
          children: [
            MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: RefreshIndicator(
                    onRefresh: _refresh,
                    child: NotificationListener(
                      child: _listView,
                      onNotification: (notification) {
                        if(notification is ScrollUpdateNotification && notification.depth == 0){
                          _onScoll(notification.metrics.pixels);
                        }
                        return false;
                      },
                    )
                ),
            ),
            _navc,
          ],
        ),
      )
    );
  }

  Widget get _listView{
    return ListView(
      children: [
        _banner,
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(localNavList: localNavList,),
        ),
        if (gridNavmodel != null) Padding(
            padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
            child: GridNav(gridNavmodel: gridNavmodel!,),
          ),


        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(subNavList: subNavList,),
        ),
        if (salesBoxModel != null) Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: salesBox(salesBoxModel: salesBoxModel!,),
        ),




      ],
    );
  }

  Widget get _navc{
    return Container(
      height: 88,
      decoration: BoxDecoration(
        color: Color.fromARGB((navcAlpha * 255).toInt(), 255, 255, 255),
      ),
      child: Column(
        children: [
          SizedBox(
            height: 50,
          ),
          Container(
            child: Row(
              children: [
                Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Row(
                    children: [
                      Text('上海',style: TextStyle(fontSize: 14,color: navcAlpha > 0.2 ? Colors.grey : Colors.white)),
                      Icon(Icons.expand_more,color: navcAlpha > 0.2 ? Colors.grey : Colors.white,),
                    ],
                  ),
                ),
                Expanded(
                    child: HomeBar(navcAlpha: navcAlpha,),),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget get _banner{
    return  Container(
      height: 160,
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: (){
              final e = bannerList?[index];
              Navigator.push(context,MaterialPageRoute(builder: (context) => FWebView(url: e?.url,title: e?.title,statusBarColor: e?.statusBarColor,hideAppBar: e?.hideAppBar,)));
            },
            child: Image.network(bannerList?[index]?.icon ?? "",fit: BoxFit.fill,),
          );
        },
        itemCount: bannerList.length ?? 0,
        pagination: SwiperPagination(),
        autoplay: true,
      ),
    );
  }

  void _onScoll(double pixels) {
    double alpha =  pixels/APPBAR_SCOLL_MAX_OFFSET;
   if (alpha < 0){
     alpha = 0;
   }else if (alpha > 1){
     alpha = 1;
   }
   setState(() {
     navcAlpha = alpha;
   });
  }

  Future<Null> _refresh() async{
    HomeDao.fetch().then((value) {
      setState(() {
        _homeModel = value;
        bannerList = _homeModel?.bannerList ?? [];
        subNavList = _homeModel?.subNavList ?? [];
        localNavList = _homeModel?.localNavList ?? [];
        gridNavmodel = _homeModel?.gridNav;
        salesBoxModel =  _homeModel?.salesBox;
        _isLoading = false;
      });
    }).catchError((e){
      _isLoading = false;
    });
    return null;
  }
}


class HomeBar extends StatefulWidget {
 final double navcAlpha;
  const HomeBar({super.key,required this.navcAlpha});

  @override
  State<HomeBar> createState() => _HomeBarState();
}

class _HomeBarState extends State<HomeBar> {
  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Row(
        children: [
          Expanded(
            child: Container(
                padding: EdgeInsets.only(left: 10),
                child:GestureDetector(
                  child: SearchTextFiled(
                    defaultText: '网红酒店',
                    enable: false,
                    spaecktap: (){
                      Navigator.push(context,MaterialPageRoute(builder: (context) => SpeakPage()));
                    },
                  ),
                  onTap: (){
                    Navigator.push(context,MaterialPageRoute(builder: (context) => SearchPage(showBackButton: true,keyWord: '网红酒店',)));
                  },
                )
            )
          ),
          Container(
              padding: EdgeInsets.only(right: 10,left: 10),
              child: Icon(Icons.comment,color: widget.navcAlpha! > 0.2 ? Colors.grey : Colors.white,),
            ),



        ],
      ),
    );
  }
}

